/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.zzslyZjyt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.zzslyZjyt.api.entity.UserEntity;
import com.pig4cloud.pigx.zzslyZjyt.mapper.UserMapper;
import com.pig4cloud.pigx.zzslyZjyt.service.UserService;
import org.springframework.stereotype.Service;

/**
 * 用户
 *
 * @author pig
 * @date 2023-11-02 11:22:47
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Override
    public R saveAll(UserEntity user) {
        String md5 = convertMD5(user.getPassword());
        user.setPassword(md5);
        return R.ok(this.save(user));
    }

    @Override
    public R updateAll(UserEntity user) {
        UserEntity byId = this.getById(user.getId());
        if (byId.getPassword().equals(user.getPassword())) {
            return R.ok(this.updateById(user));
        } else {
            String md5 = convertMD5(user.getPassword());
            user.setPassword(md5);
            return R.ok(this.updateById(user));
        }
    }

    @Override
    public R login(String userName, String password) {
        LambdaQueryWrapper<UserEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserEntity::getUserName, userName);
        UserEntity one = this.getOne(wrapper);
        if (one == null) {
            return R.failed("账号错误或该账号暂无注册");
        }
        String md5 = convertMD5(password);
        if (md5.equals(one.getPassword())) {
            return R.ok("登录成功");
        } else {
            return R.failed("密码错误");
        }
    }


    public String convertMD5(String inStr) {

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;

    }
}
